<template>
  <div class="websocket-wrapper">
    <slot></slot>
  </div>
</template>

<script type="text/ecmascript-6">
  import {getAuthCookie} from '../../common/js/cookie-util'

  export default {
    name: 'websocket-wrapper',
    props: ['wsuri', 'destroyed'],
    components: {},
    data() {
      return {
        websock: null,
        retryInterval: undefined, //重连的定时器
        retry: false, //是否已经开始重连
        healthyInterval: undefined //心跳
      }
    },
    mounted() {
    },
    destroyed() {
      if (this.destroyed === true) {
        this.stopRetryConnection()
        clearInterval(this.healthyInterval)
        this.retry = true //这里离开组件销毁连接后，防止重连
        this.close() //离开路由之后断开websocket连接
        console.log('[destroyed] websocket all log close')
      }
    },
    methods: {
      initWebSocket() { //初始化weosocket
        //todo 初始化之前，最好先判定token是否有效，如果无效的情况下，直接无需在连接ws
        this.websock = new WebSocket(this.wsuri + '/' + getAuthCookie())
        this.websock.onmessage = this.websocketonmessage
        this.websock.onopen = this.websocketonopen
        this.websock.onerror = this.websocketonerror
        this.websock.onclose = this.websocketclose
      },
      websocketonopen() { //连接建立之后执行send方法发送数据
        console.log('建立连接: ' + this.wsuri)
        this.stopRetryConnection()

        //建立心跳传输
        if (this.healthyInterval) {
          clearInterval(this.healthyInterval)
        }
        this.healthyInterval = setInterval(this.healthySendMsg, 15000) //心跳
      },
      websocketonerror() { //连接建立失败重连
        this.retryConnection()
      },
      websocketonmessage(msg) { //数据接收
        this.$emit('onMessage', JSON.parse(msg.data))
      },
      websocketsend(data) { //数据发送
        this.websock.send(data)
      },
      websocketclose(e) { //关闭
        console.log('断开连接', e)
        this.retryConnection()
      },
      healthySendMsg() {
        this.websocketsend('healthy')
      },
      close() { // 离开路由后记得销毁, 各自业务而定
        this.websock.close()
      },
      retryConnection() {
        if (this.retry) {
          return
        }
        this.retry = true
        this.retryInterval = setInterval(this.initWebSocket, 3000)
      },
      stopRetryConnection() {
        clearInterval(this.retryInterval)
        this.retry = false
      }
    }
  }
</script>

<style lang="stylus" type="text/stylus" scoped>
</style>
